package com.mini.cn.goods.lottery;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

@Slf4j
public class NumberManager {

  private volatile static NumberManager numberManager;
  private List<Integer> speed;//号码箱子
  private final static byte[] lock = new byte[0];

  private NumberManager() {
    speed = new ArrayList<Integer>();
  }

  public static NumberManager getIntanceNumberManager() {
    if (numberManager == null) {
      synchronized (lock) {
        if (numberManager == null) {
          numberManager = new NumberManager();
        }
      }
    }
    return numberManager;
  }


  /**
   * 初始化号码箱子
   *
   * @param number 生成号码的个数
   */
  public void init(int number) {
    speed.clear();
    for (int i = 0; i < number; i++) {
      speed.add(i);
    }
  }

  /**
   * 抽号码
   *
   * @param number
   * @return
   */
  public synchronized List<Integer> takeNumber(int number) {
    int size = speed.size();
    List<Integer> nms = null;
    if(size>0) {
      if (size > number) {
        nms = new ArrayList<Integer>();
        //分配号码
        for (int i = 0; i < number; i++) {
          int pos = ThreadLocalRandom.current().nextInt(speed.size());
          log.info("pos="+pos);
          int realNumber = speed.get(pos);
          nms.add(realNumber);
          speed.remove(pos);
        }
      } else if (size == number) {
        nms = new ArrayList<Integer>();
        nms.addAll(speed);
        speed.clear();
      }
    }
    return nms;
  }


  public static void main(String[] agrs){
    //初始化
    NumberManager.getIntanceNumberManager().init(200);
    List<Integer> numbers= NumberManager.getIntanceNumberManager().takeNumber(199);
    for(Integer number:numbers){
      System.out.println(number);
    }
  }
}
